package cn.lsh.main;

import cn.lsh.combiner.WeatherCombiner;
import cn.lsh.comparator.WeatherGroupComparator;
import cn.lsh.comparator.WeatherSortComparator;
import cn.lsh.mapper.WeatherMapper;
import cn.lsh.partitioner.WeatherPartitioner;
import cn.lsh.reducer.WeatherReduce;
import cn.lsh.writable.Weather;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class WeatherDriver {

	public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration(true);
		Job job = Job.getInstance(conf);

		job.setJarByClass(WeatherDriver.class);

		//----Mapper setting----
		//设置mapper以及map输出类型
		job.setMapperClass(WeatherMapper.class);
		job.setMapOutputKeyClass(Weather.class);
		job.setMapOutputValueClass(IntWritable.class);

		//设置自定义分区器
		job.setPartitionerClass(WeatherPartitioner.class);
		//设置自定义排序比较器
		job.setSortComparatorClass(WeatherSortComparator.class);
		//设置自定义combiner合并器
		job.setCombinerClass(WeatherCombiner.class);
		//----Mapper setting----

		//----Reducer setting----
		//设置自定义分组比较器
		job.setGroupingComparatorClass(WeatherGroupComparator.class);

		//设置reducer
		job.setReducerClass(WeatherReduce.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);

		//设置reduce task个数，默认1个
		job.setNumReduceTasks(2);
		//----Reducer setting----

		//设置输入
		FileInputFormat.addInputPath(job, new Path(args[0]));

		Path output = new Path(args[1]);
		FileSystem fs = output.getFileSystem(conf);
		if (fs.exists(output)) {
			//如果输出目录存在，递归删除，MapReduce不会杀出输出目录
			fs.delete(output, true);
		}

		// 设置输出
		FileOutputFormat.setOutputPath(job, output);

		//提交任务
		job.waitForCompletion(true);
	}
}
